package com.luke.boot.spring_security.userdetail_service;

import com.luke.boot.spring_security.dao.UserDao;
import com.luke.boot.spring_security.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 自定义UserDetailsService实现类
 */
@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    //根据用户名返回用户详情信息UserDetails
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*UserDetails userDetails = User.withUsername("zhangsan")
                .password("$2a$10$8TVq/IoR9wYLsjuwW5yi3eKFIep8H20pfY/ulHuKqm1WqqTpz1xIW")//BCrypt
                .authorities("p1").build();*/

        //从数据库查询用户信息
        UserDto userDto = userDao.getUserByUsername(username);
        if(userDto == null){
            return null;//如果查询不到用户返回null，交给SpringSecurity的Provider来抛出异常
        }

        //查询用户权限信息
        List<String> permissions = userDao.findPermissionsByUserId(userDto.getId());
        String[] perArray = new String[permissions.size()];
        permissions.toArray(perArray);

        //转换成SpringSecurity框架的UserDetails
        UserDetails userDetails = User.withUsername(userDto.getUsername()).
                password(userDto.getPassword()).authorities(perArray).build();
        return userDetails;
    }

}
